<template>
    <el-form ref="editTictData" :rules="rules" :model="editTictData"
             label-position="top" class="addTictStyle">
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <h3 class="ticTitle">票务基本信息</h3>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务名称 :" prop="name">
            <el-input v-model="editTictData.name" placeholder="请输入票务名称" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务种类 :" prop="tictKind" >
            <el-select v-model="editTictData.tictKind" filterable placeholder="请选择票务种类" style="width:100%">
              <el-option
                v-for="kinds in tickValue"
                :key="kinds.code"
                :label="kinds.name"
                :value="kinds.code"
              >{{kinds.name}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="所属场馆 :" prop="yardName">
            <el-select v-model="editTictData.yardName" filterable placeholder="请选择场地"   @change='getValue' style="width:100%">
              <el-option
                v-for="item in yardOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code">
                {{item.name}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="场地代码 :" prop="yardCode" hidden>
            <el-input v-model="editTictData.yardCode" placeholder="选择场地后自动填充" disabled ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票代码 :" prop="code" hidden>
            <el-input v-model="editTictData.code" placeholder="请输入票代码" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="商户UUID :" prop="merchUuid" v-show="false">
            <el-input v-model="editTictData.merchUuid" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="商户信息 :" prop="merchName">
            <el-input v-model="editTictData.merchName" placeholder="商户名称"  ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="验证方式 :" prop="validation">
            <el-select v-model="editTictData.validation" filterable placeholder="请选择验证方式" style="width:100%" multiple >
              <el-option v-for="validation in validationOptions"
                         :key="validation.code"
                         :label="validation.name"
                         :value="validation.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--        <el-col :span="10">-->
      <!--          <el-form-item label="票据状态 :" prop="valid">-->
      <!--            <el-select v-model="editTictData.valid" filterable placeholder="请票据状态" style="">-->
      <!--              <el-option-->
      <!--                v-for="( ky, val ) in validOptions"-->
      <!--                :key="val"-->
      <!--                :label="ky"-->
      <!--                :value="val">-->
      <!--                {{ky}}-->
      <!--              </el-option>-->
      <!--            </el-select>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="退票 :" prop="recedeTick">
            <el-switch
              v-model="editTictData.recedeTick"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="100"
              inactive-value="0"
              @change='checkRecedeTick'
            >
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item  label="可退日期 :" prop="recedeDate" v-if="this.editTictData.recedeTick==100" >
            <el-date-picker
              v-model="editTictData.recedeDate"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm:ss"
              style="width:100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票面图片 :">
            <el-upload ref="upload" action="''"
                       :on-remove="handleRemove"
                       list-type="picture-card"
                       :file-list="showImgs"
                       :auto-upload="false"
                       :http-request="uploadFile"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务介绍 :" prop="info" >
            <el-input v-model="editTictData.info" placeholder="请输入票务介绍" type="textarea" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="详情图 :">
            <el-upload ref="detailUpload" action="''"
                       :on-remove="detailRemove"
                       list-type="picture-card"
                       :file-list="detailShowImgs"
                       :auto-upload="false"
                       :http-request="uploadFileDeatail"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="轮播图 :">
            <el-upload ref="carouseUpload" action="''"
                       :on-remove="carouseRemove"
                       list-type="picture-card"
                       :file-list="carouselShowImgs"
                       :auto-upload="false"
                       :http-request="uploadFileCarouse"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-footer height="80px">
        <el-row style="display: flex;justify-content: center;align-items: center;">
          <el-button @click="submit" type="primary">
            保存
          </el-button>
          <el-button @click="closDisplay">
            取消
          </el-button>
        </el-row>
      </el-footer>
    </el-form>
</template>

<script>
import { replaceSpacesObj } from '../../../utils/webUtils.js'
import {} from "../../../styles/addTict.scss"

export default {
  name: 'EditTict',
  components: {  },
  props: {
    tictUuid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uuid: this.tictUuid,
      editTictData: {
        name: '',
        code: '',
        yardName: '',
        yardCode: '',
        info: '',
        merchUuid: '',
        merchName: '',
        // valid: '',
        tictKind: '',
        validation: [],
        recedeDate: '',
        recedeTick: '',
        imgStr:'',
        detailImgStr:'',
        carouseImgStr:''
      },
      validOptions: {},
      yardOptions: [],
      mercList: [],
      validationOptions: [],
      tickValue: [],
      merchants: { name: '', uuid: '' },
      showImgs:[],
      list:[],
      detailShowImgs:[],
      detailList:[],
      carouselShowImgs:[],
      carouseList:[],
        rules: {
          name: [
            { required: true, message: '票名称不能为空', trigger: 'blur' },
          ],
          tictKind: [
            { required: true, message: '票务种类不能为空', trigger: 'blur' },
          ],
          yardName: [
            { required: true, message: '所属场馆不能为空', trigger: 'blur' },
          ],
          validation: [
            { required: true, message: '验证方式不能为空', trigger: 'blur' },
          ],

      },
      info: '',
      infoShow: false,
      tictObj: {}
    }
  },
  // 深度监听父组件的props传值
  watch: {
    tictUuid(val) {
      this.uuid = val
      this.queryTict()
    }
  },
  mounted() {
    this.uuid=this.$route.params.uuid
    this.queryValid()
    this.queryTict()
    this.queryYard()
    // 票务种类
    this.queryKinds()
    // 验证方式
    this.queryvalidationOptions()
    //图片回显

  },
  methods: {
    //图片回显
    quertImgRelook(){
      if(this.editTictData.imgStr != null && this.editTictData.imgStr != ''){
        this.showImgs = [];
        JSON.parse(this.editTictData.imgStr).forEach(res=>{
          this.showImgs.push({'name':res.filename,'url':"http://39.106.30.94/respu/"+res.url})
        })
      }
      if(this.editTictData.detailImgStr != null && this.editTictData.detailImgStr != '') {
        this.detailShowImgs=[]
        JSON.parse(this.editTictData.detailImgStr).forEach(res => {
          this.detailShowImgs.push({'name': res.filename, 'url': "http://39.106.30.94/respu/" + res.url})
        })
      }
      if(this.editTictData.carouseImgStr != null && this.editTictData.carouseImgStr != '') {
        this.carouselShowImgs=[]
        JSON.parse(this.editTictData.carouseImgStr).forEach(res => {
          this.carouselShowImgs.push({'name': res.filename, 'url': "http://39.106.30.94/respu/" + res.url})
        })
      }
    },
    carouseRemove(file, fileList) {
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);

        }
      }
      this.carouselShowImgs=fileList
      if(this.carouselShowImgs.length>0) {
        this.carouselShowImgs.forEach(res => {
          this.carouseList.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.carouseImgStr = JSON.stringify(this.carouseList)
      }else{
        this.editTictData.carouseImgStr =''
      }
    },
    detailRemove(file, fileList) {
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);

        }
      }
      this.detailShowImgs=fileList
      this.detailList=[]
      if (this.detailShowImgs.length>0){
        this.detailShowImgs.forEach(res=>{
          this.detailList.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.activityHeadImgStr=JSON.stringify(this.detailList)
      }else{
        this.editTictData.activityHeadImgStr=''
      }
    },
    handleRemove(file, fileList) {
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);
        }
      }
      this.showImgs=fileList
      this.list=[]
      if(this.showImgs.length>0) {
        this.showImgs.forEach(res => {
          this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.imgStr = JSON.stringify(this.list)
      }else{
        this.editTictData.imgStr=''
      }

    },
    uploadFile(item){
      if(item.file=!''&&item.file!=null){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "https://whcm.21theone.cn:9010/tck/kdi/tict/"+this.tictObj.uuid+"/imgup",formData
      ).then(res=>{
        this.list.push({'filename':res.data.filename,'url':res.data.url})
        this.editTictData.imgStr = JSON.stringify(this.list)
        this.uploadImg();
      }).catch(error => {
        console.log(error);
        this.info = "图片上传失败！";
        this.dataFail("上传图片失败")
      });
      }else{
        this.editTictData.imgStr = ''
      }
    },
    uploadFileCarouse(item){
      if(item.file=!''&&item.file!=null){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "https://whcm.21theone.cn:9010/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        this.carouseList.push({'filename':res.data.filename,'url':res.data.url})
        this.editTictData.carouseImgStr = JSON.stringify(this.carouseList)
        this.uploadImg();
      }).catch(error => {
        console.log(error);
        this.info = "图片上传失败！";
        this.dataFail("上传图片失败")
      });
      }else{
        this.editTictData.carouseImgStr = ''
      }
    },
    uploadFileDeatail(item){
      if(item.file!=null&&item.file!=''){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "https://whcm.21theone.cn:9010/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        this.detailList.push({'filename':res.data.filename,'url':res.data.url})
        this.editTictData.detailImgStr = JSON.stringify(this.detailList)
        this.uploadImg();
      }).catch(error => {
        console.log(error);
        this.info = "图片上传失败！";
        this.dataFail("上传图片失败")
      });
      }else{
        this.editTictData.detailImgStr = ''
      }
    },
    uploadImg(){
      this.axios.request({
        method: "put",
        url: "./tck/kdi/tict/"+this.uuid+"/img",
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        },
        data: replaceSpacesObj(this.editTictData)
      }).then(() => {

      }).catch(error => {
        console.log(error);
        this.info = '上传图片后回写imgStr数据失败！';
        this.infoShow = true;
        this.dataFail("上传图片回写数据失败")
      });
    },

    sucess() {
      this.$notify({
        title: '成功',
        message: '票务修改成功',
        type: 'success'
      });
      this.$emit("close");
    },
    fail() {
      this.$notify({
        title: '失败',
        message: '票务修改失败',
        type: 'success'
      });
    },
    // 监听
    checkRecedeTick() {
      if (this.editTictData.recedeTick === '0') {
        this.editTictData.recedeDate = ''
      }
    },
    // 票务种类
    queryKinds() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_KINDS',
          params: {}
        })
        .then(response => {
          this.tickValue = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 票务验证方式
    queryvalidationOptions() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_VOLIDATION',
          params: {}
        })
        .then(response => {
          this.validationOptions = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 查询后端票据有效标识枚举
    queryValid() {
      this.axios
        .request({
          method: 'get',
          url: './tck/kdi/enums/Valid',
          params: {}
        })
        .then(response => {
          this.validOptions = response.data.data
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 查询场地
    queryYard() {
      this.axios
        .request({
          method: 'get',
          url: './ope/kdi/yard/search/findAllTree',
          params: {}
        })
        .then(response => {
          this.yardOptions = response.data[0].subs
        })
        .catch(error => {
          console.log(error)
        })
    },
    getValue() {
      this.yardOptions.forEach(list => {
        if (list.name === this.editTictData.yardName) {
          this.editTictData.yardCode = list.code
        }
      })
    },
    // 通过uuid查询当前对象信息
    queryTict() {
      this.axios.request({
        method: 'get',
        url: './tck/kdi/tict/' + this.uuid,
        headers: {},
        params: {}
      }).then(response => {
        this.insertTict(response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },
    insertTict(tict) {
      this.editTictData.name = tict.name
      this.editTictData.code = tict.code
      this.editTictData.yardName = tict.yardName
      this.editTictData.yardCode = tict.yardCode
      this.editTictData.info = tict.info
      this.editTictData.merchUuid = tict.merchUuid
      this.editTictData.merchName = tict.merchName
      // this.editTictData.valid = tict.valid
      this.editTictData.imgStr = tict.imgStr
      this.editTictData.tictKind = tict.tictKind
      this.editTictData.recedeTick = tict.recedeTick
      this.editTictData.recedeDate = tict.recedeDate
      this.editTictData.validation = JSON.parse(tict.validation)
      this.editTictData.imgStr=tict.imgStr
      this.editTictData.detailImgStr=tict.detailImgStr
      this.editTictData.carouseImgStr=tict.carouseImgStr
      this.quertImgRelook()
    },
    submit() {
      this.$refs['editTictData'].validate((valid) => {
        if (!valid) {
          return
        }
        this.editTictData.validation=JSON.stringify(this.editTictData.validation)
        this.axios.request({
          method: 'put',
          url: './tck/kdi/tict/' + this.uuid,
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: replaceSpacesObj(this.editTictData)
        }).then((response) => {
          this.tictObj = response.data
          this.dataSucess("修改数据成功");
          this.imgSubmit();
          this.closDisplay()
        }).catch(error => {
          console.log(error)
          this.info = '修改失败'
          this.dataFail();
        })
      })
    },
    uploadFileCarouse(item){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.carouseList.push({'filename':data.filename,'url':data.url})

        this.editTictData.carouseImgStr = JSON.stringify(this.carouseList)
        if(this.editTictData.carouseImgStr.length>0){
          this.uploadImg();
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传图片失败")
      });
    },
    uploadFile(item){
      let formData = new FormData();

      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.list.push({'filename':data.filename,'url':data.url})

        this.editTictData.imgStr = JSON.stringify(this.list)
        if(this.editTictData.imgStr.length>0){
          this.uploadImg();
        }

      }).catch(error => {
        this.dataFail("上传图片失败")
      });
    },
    uploadFileDeatail(item){

      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.detailList.push({'filename':data.filename,'url':data.url})
        this.editTictData.detailImgStr = JSON.stringify(this.detailList)
        if(this.editTictData.detailImgStr.length>0){
          this.uploadImg();
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传图片失败")
      });
    },
    imgSubmit(){
      if(this.showImgs.length>0) {
        this.list=[]
        this.showImgs.forEach(res => {
          this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.imgStr = JSON.stringify(this.list)
      }
      if (this.detailShowImgs.length>0){
        this.detailList=[]
        this.detailShowImgs.forEach(res=>{
          this.detailList.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.detailImgStr=JSON.stringify(this.detailList)
      }
      if(this.carouselShowImgs.length>0) {
        this.carouseList=[]
        this.carouselShowImgs.forEach(res => {
          this.carouseList.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tic'))})
        })
        this.editTictData.detailImgStr = JSON.stringify(this.carouseList)
      }
      this.$refs.detailUpload.submit()
      this.$refs.upload.submit()
      this.$refs.carouseUpload.submit()


    },
    closDisplay(){
      this.$router.push("/tictReport")
    },
    dataSucess(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success'
      });
    },
    dataFail(message) {
      this.$notify({
        title: '失败',
        message: message,
        type: 'error'
      });
    },
    cleanTict() {
      this.$router.push('/tictReport/')
    },
    cleanHrom() {
      this.$refs.upload.clearFiles();
      this.$refs.carouseUpload.clearFiles();
      this.$refs.detailUpload.clearFiles();
        this.editTictData = {
          name: '',
          code: '',
          yardName: '',
          yardCode: '',
          info: '',
          merchUuid: '',
          merchName: '',
          valid: '',
          tictKind: '',
          validation: '',
          recedeDate: '',
          recedeTick: '',
          detailImgStr: '',
          carouseImgStr: '',
          imgStr:''
        }

    }
  }
}
</script>

<style scoped lang="scss">


</style>
